package com.gaozhaoyang.download;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet("/download")
public class DownLoadServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取用户下载的资源名称
        String fileName = req.getParameter("fileName");
        //通知浏览器以下载的形式打开资源
        resp.setHeader("Content-disposition","attachment;fileName=" + URLEncoder.encode(fileName,"utf-8"));
        //根据文件名找到该资源在服务器中真实路径
        String path = req.getServletContext().getRealPath("/file/" + fileName);
        //创建文件字节输入流对象
        FileInputStream fis = new FileInputStream(path);
        byte arr[] = new byte[1024 * 8];
        int len;
        //获取响应流
        ServletOutputStream fos = resp.getOutputStream();
        while ((len = fis.read(arr)) != -1){
            fos.write(arr,0,len);
        }
        //释放资源
        fos.close();
        fis.close();
    }
}
